/**
 * Created by Void on 2017/9/18.
 */

import {
    Component, ViewEncapsulation, OnInit, ElementRef, NgZone, Renderer,
    ComponentFactoryResolver, ErrorHandler, Input, ChangeDetectorRef, AfterViewInit, OnDestroy, ViewContainerRef,
    ViewChild
} from "@angular/core";
import {
    NavControllerBase, App, Config, Platform, Keyboard, GestureController, DeepLinker,
    DomController, NavOptions
} from "ionic-angular";
import {SuperTabs} from "./super-tabs";
import {TransitionController} from "ionic-angular/transitions/transition-controller";
@Component({
    selector:'super-tab',
    template:`<div #viewport></div><div class="nav-decor"></div>`,
    encapsulation:ViewEncapsulation.None
})

export class SuperTab extends NavControllerBase implements OnInit,AfterViewInit,OnDestroy{

    @Input() title:string;
    @Input() root:any; // pageComponent
    @Input() rootParams:any;
    @Input('id') tabId:string;
    @Input() badge:number;

    private loaded:boolean = false; // 判断本页面是否已经被加载

    private init:Promise<any>;
    private initResolve:Function;

    // 设置tab的页面
    @ViewChild('viewport', {read: ViewContainerRef})
    set _vp(val: ViewContainerRef) {
        this.setViewport(val);
    }

    constructor(
        parent:SuperTabs,
        app:App,
        config:Config,
        plt:Platform,
        keyboard:Keyboard,
        el:ElementRef,
        zone:NgZone,
        rnd:Renderer,
        cfr:ComponentFactoryResolver,
        gestureCtrl:GestureController,
        trnsCtrl:TransitionController,
        linker:DeepLinker,
        domCtrl:DomController,
        errHandler:ErrorHandler,
        private cd:ChangeDetectorRef, // 双向检测变更类 类似angular1的$digest(脏检测); angular4性能的提升 该类起了很大作用
    ){
        super(parent,app,config,plt,el,zone,rnd,cfr,gestureCtrl,trnsCtrl,linker,domCtrl,errHandler);
        this.init = new Promise<void>( resolve => this.initResolve = resolve);
    }

    ngOnInit(){
        this.parent.addTab(this);
    }

    ngAfterViewInit(){
        // 初始化完成
        this.initResolve();
    }
    ngOnDestroy(){
        this.destroy();
    }

    // 将该页面添加到导航控制器中
    load(load:boolean){
        // 因为 页面左右滑动 所以 判断页面是否被加载 防止重复加载,浪费性能
        if (load && !this.loaded){
            this.init.then( () => {
                this.push(this.root,this.rootParams,{animate:false});
                this.loaded = true;
            })
        }
    }

    // 设置 活动页面 和 非活动页面的 变更检测。 性能优化
    setActive(active:boolean){
        if (active){
            this.cd.reattach(); // 重新加入 检测变更页面渲染队列。(加入队列后就自动检测了)
            this.cd.detectChanges(); // 手动 变更检测一次
        }else if (!active){
            this.cd.detach(); // 当不是活动视图时，从检测队列中移除
        }
    }

    setWidth(width:number){
        // 因为该类继承于 navcontroller 又继承与 ion 所以可以使用 ion 的方法
        this.setElementStyle('width',width + 'px');
    }

    // 返回根控制器(super-tabs);
    gotoRoot(opts:NavOptions):Promise<any>{
        return this.setRoot(this.root,this.rootParams,opts,null);
    }
}